package com.uziot.bucket.minio;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author shidt
 * @version V1.0
 * @className MinioController
 * @date 2020-01-18 23:14:55
 * @description 主要实现了对象存储服务的操作
 * MinIO对象存储管理 ，需要在Linux中安装对象存储服务，并在代码中调用
 */

@Slf4j
@RestController
@RequestMapping("/minio")
public class MinioController {

    @Autowired
    private MinioClientComponent minioClientComponent;
    @Autowired
    private MinioConfig minioConfig;

    @PostMapping(value = "/upload")
    public MinioUploadDto upload(@RequestPart("file") MultipartFile file) {
        MinioUploadDto minioUploadDto = new MinioUploadDto();
        try {
            String filename = file.getOriginalFilename();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            // 设置存储对象名称
            String objectName = sdf.format(new Date()) + "/" + filename;
            // 使用putObject上传一个文件到存储桶中
            String bucketName = minioConfig.getBucketName();
            String file1 = minioClientComponent.uploadInputStream(bucketName, objectName, file.getInputStream());
            log.info("文件上传成功!");
            minioUploadDto.setName(objectName);
            minioUploadDto.setUrl(file1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return minioUploadDto;
    }
}